package cn.xiuxius.askbox.common.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.UUID;


@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Component
public class MinioUtil {
    @Value("${askbox.minio.oss.endpoint}")
    private String endpoint;
    @Value("${askbox.minio.oss.access-key}")
    private String accessKey;
    @Value("${askbox.minio.oss.secret-key}")
    private String secretKey;
    @Value("${askbox.minio.oss.bucket-name}")
    private String bucketName;
    public String upload(InputStream in, String extName) throws Exception {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        String fileName = UUID.randomUUID().toString() + extName;
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(in, in.available(), -1)
                .build();
        minioClient.putObject(putObjectArgs);
        return endpoint + "/" + bucketName + "/" + fileName;
    }

}
